﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Layout;
using Inaction.Mapping;
using Inaction.UI.Common;
using System;
using System.Linq;
using System.Windows.Forms;

namespace Inaction.UI.Settings
{
    internal static class GridSetting
    {
        #region SetGridProperties
        public static void SetGridProperties(GridControl grid)
        {
            if (grid.UseEmbeddedNavigator != true)
            {
                grid.UseEmbeddedNavigator = true;
                grid.EmbeddedNavigator.Buttons.Append.Visible = false;
                grid.EmbeddedNavigator.Buttons.CancelEdit.Visible = false;
                grid.EmbeddedNavigator.Buttons.Edit.Visible = false;
                grid.EmbeddedNavigator.Buttons.EndEdit.Visible = false;
                grid.EmbeddedNavigator.Buttons.Remove.Visible = false;
            }
            if (grid.MainView is GridView)
            {
                var view = (GridView)grid.MainView;
                view.OptionsDetail.AllowZoomDetail = false;
                view.OptionsDetail.EnableMasterViewMode = false;
                view.OptionsDetail.ShowDetailTabs = false;
                view.OptionsDetail.SmartDetailExpand = false;
                view.OptionsView.ColumnAutoWidth = false;
                view.OptionsView.ShowGroupPanel = false;
                view.OptionsNavigation.EnterMoveNextColumn = true;
                SetViewInplaceEditProperties(view);
                SetGridColumn(grid);
            }
            if (grid.MainView is LayoutView)
            {
                var view = grid.MainView as LayoutView;
                view.CardHorzInterval = 0;
                view.CardVertInterval = 0;
                view.OptionsBehavior.AllowExpandCollapse = false;
                view.OptionsBehavior.AutoPopulateColumns = false;
                view.OptionsBehavior.AutoSelectAllInEditor = false;
                view.OptionsBehavior.Editable = false;
                view.OptionsBehavior.ScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Auto;
                view.OptionsFilter.AllowFilterEditor = false;
                view.OptionsItemText.AlignMode = DevExpress.XtraGrid.Views.Layout.FieldTextAlignMode.AutoSize;
                view.OptionsItemText.TextToControlDistance = 0;
                view.OptionsView.AllowHotTrackFields = false;
                view.OptionsView.ShowCardCaption = false;
                view.OptionsView.ShowCardExpandButton = false;
                view.OptionsView.ShowCardLines = false;
                view.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
                view.OptionsView.ShowHeaderPanel = false;
                view.OptionsView.ViewMode = DevExpress.XtraGrid.Views.Layout.LayoutViewMode.MultiColumn;
            }
        }

        private static void SetViewInplaceEditProperties(GridView gv)
        {
            foreach (GridColumn column in gv.Columns)
            {
                var col = column as GridColumn;
                if (col.ColumnEdit != null)
                {
                    if (!gv.GridControl.RepositoryItems.Contains(col.ColumnEdit))
                    {
                        gv.GridControl.RepositoryItems.Add(col.ColumnEdit);
                    }
                }
                if (col.ColumnEdit is RepositoryItemLookUpEdit)
                {
                    var lue = col.ColumnEdit as RepositoryItemLookUpEdit;
                    lue.ImmediatePopup = true;
                    lue.NullText = string.Empty;
                    lue.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                    lue.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                    lue.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.OnlyInPopup;
                }
                if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                {
                    var lue = col.ColumnEdit as RepositoryItemGridLookUpEdit;
                    lue.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                    lue.ImmediatePopup = true;
                    lue.NullText = string.Empty;
                    lue.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                }
                if (col.ColumnType.Equals(typeof(DateTime)) || col.ColumnType.Equals(typeof(DateTime?)))
                {
                    if (col.FieldName.EndsWith("DATE", StringComparison.OrdinalIgnoreCase))
                    {
                        col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                        col.DisplayFormat.FormatString = "d";
                    }
                    else if (col.FieldName.EndsWith("TIME", StringComparison.OrdinalIgnoreCase))
                    {
                        col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                        col.DisplayFormat.FormatString = "G";
                    }
                }
            }
        }
        #endregion

        #region SetGridColumn
        public static void SetGridColumn(GridControl gridControl)
        {
            var gridView = gridControl.MainView as GridView;
            var bindingSource = gridControl.DataSource as BindingSource;
            ClassInfo classInfo = null;
            if (bindingSource != null)
            {
                try
                {
                    var t = BindingHelper.GetListItemType(bindingSource);
                    if (t.GetInterface(typeof(Inaction.Core.ISavable).FullName) != null)
                    {
                        classInfo = ClassInfo.LoadInfo(t);
                    }
                }
                catch { }
            }
            if (gridView == null) return;
            foreach (GridColumn column in gridView.Columns)
            {
                if (column.ColumnEdit != null)
                {
                    if (column.ColumnEdit is RepositoryItemLookUpEditBase)
                    {
                        var lue = column.ColumnEdit as RepositoryItemLookUpEditBase;
                        lue.NullText = string.Empty;
                        lue.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                        lue.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                        lue.ImmediatePopup = true;
                        lue.CloseUpKey = new DevExpress.Utils.KeyShortcut(Keys.Space);
                    }
                    continue;
                }
                if (classInfo != null && classInfo.ColumnProperties.Values.Any(p => p.Name == column.FieldName))
                {
                    if (!classInfo.NameProperties.ContainsKey(column.FieldName)) continue;
                    var property = classInfo.NameProperties[column.FieldName];

                    #region ForeignKey
                    if (property.Column.IsForeignKey)
                    {
                        var lue = column.ColumnEdit as RepositoryItemGridLookUpEdit;
                        if (lue == null)
                        {
                            lue = new RepositoryItemGridLookUpEdit();
                            lue.View.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
                            lue.View.OptionsSelection.EnableAppearanceFocusedCell = false;
                            lue.View.OptionsView.ShowAutoFilterRow = true;
                            lue.View.OptionsView.ShowGroupPanel = false;
                            lue.NullText = string.Empty;
                            lue.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
                            lue.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
                            lue.ImmediatePopup = true;
                            lue.CloseUpKey = new DevExpress.Utils.KeyShortcut(Keys.Space);
                            column.ColumnEdit = lue;
                            BarManagerDesigner.WorkingBarManager.Container.Add(lue);
                            if (!gridControl.RepositoryItems.Contains(column.ColumnEdit))
                            {
                                gridControl.RepositoryItems.Add(column.ColumnEdit);
                            }
                        }
                        lue.NullText = string.Empty;
                        if (lue.DataSource != null) continue;

                        var foreignKey = property.Column.Table.ForeignKeys.FirstOrDefault(p => p.Column == p.Column);
                        var foreignBs = TableClassTypeHelper.GetClassBindingSource(foreignKey.ReferenceTable.Name);
                        if (foreignBs != null)
                        {
                            lue.DataSource = foreignBs;
                            lue.ValueMember = foreignKey.Table.PrimaryKey.Name;
                            var foreignType = BindingHelper.GetListItemType(foreignBs);
                            var foreignClassInfo = ClassInfo.LoadInfo(foreignType);
                            var nameColumns = foreignClassInfo.NameProperties.Where(p => p.Value.Name.EndsWith("Name", StringComparison.OrdinalIgnoreCase));
                            var codeColumns = foreignClassInfo.NameProperties.Where(p => p.Value.Name.EndsWith("Code", StringComparison.OrdinalIgnoreCase));
                            if (nameColumns.Count() > 0)
                            {
                                lue.DisplayMember = nameColumns.First().Value.Name;
                            }
                            foreach (var codeColumn in codeColumns)
                            {
                                lue.View.Columns.AddVisible(codeColumn.Value.Name);
                            }
                            foreach (var nameColumn in nameColumns)
                            {
                                lue.View.Columns.AddVisible(nameColumn.Value.Name);
                            }
                        }
                    }
                    #endregion
                }
            }
        }
        #endregion
    }
}
